package com.yxsk.relay.job.admin.core.executor;

import com.yxsk.relay.job.admin.core.executor.context.JobExecuteContext;
import com.yxsk.relay.job.admin.core.executor.listener.JobExecuteListener;

/**
 * @Author 11376
 * @CreaTime 2019/6/28 9:50
 * @Description
 */
public abstract class ListenableJobExecutor<T extends JobExecuteContext> implements JobExecutor<T> {

    protected JobExecuteListener executeListener;

    protected T context;

    protected ListenableJobExecutor(JobExecuteListener executeListener) {
        this.executeListener = executeListener;
    }

    @Override
    public final void execute(T context) {
        this.context = context;
        // 执行前置监听
        if (this.executeListener != null) {
            this.executeListener.executeBefore(context);
        }

        try {
            this.doWork();
            if (this.executeListener != null) {
                this.executeListener.onFinish(context);
            }
        } catch (Throwable e) {
            if (this.executeListener != null) {
                this.executeListener.onError(context, e);
            }
        } finally {
            if (this.executeListener != null) {
                this.executeListener.executeAfter(context);
            }
        }
    }

    protected abstract void doWork();

}
